﻿using Mapster;
using MyMapster;
using Newtonsoft.Json;

Console.WriteLine("1. 简单类型转换");
Console.WriteLine(123.Adapt<string>()); // 等同于: 123.ToString();
Console.WriteLine("321".Adapt<int>());

Console.WriteLine("\n2. 对象转换A到B");
var dto = new UserDto { Id = 1, Name = "tom", Email = "tom@gmail.com" };
Console.WriteLine(dto.Adapt<UserDao>());

Console.WriteLine("\n3. 对象转换B到A");
var dao = new UserDao { Name = "jack", Email = "jack@foxmail.com", Version = "v1.0.0" };
Console.WriteLine(dao.Adapt<UserDto>());

Console.WriteLine("\n4. 集合类型转换");
var arr = new[] { 1, 2, 3, 4, 5 };
Console.WriteLine(JsonConvert.SerializeObject(arr.Adapt<string[]>()));  //转换为字符串数组

Console.WriteLine("\n5. 对象转字典");
var dic = dto.Adapt<Dictionary<string, object>>();
Console.WriteLine(JsonConvert.SerializeObject(dic));

Console.WriteLine("\n6. 自定义映射(参数化)");
var cfg = new TypeAdapterConfig();
cfg.NewConfig<NameSplit, NameMerge>().Map(dest => dest.FullName, src => $"{src.FirstName}·{src.LastName}");

var gm = new NameSplit { FirstName = "Jim", LastName = "Green", Language = "English" };
Console.WriteLine(gm.Adapt<NameMerge>(cfg));

Console.WriteLine("\n7. 自定义映射(全局配置)");
// NewConfig()用于创建一个新的适配器配置
// ForType() 获取一个已经存在的适配器配置
TypeAdapterConfig<NameSplit, NameMerge>.ForType().Ignore(dest => dest.Language!).IgnoreNullValues(true)
    .Map(dest => dest.FullName, src => $"{src.FirstName}-{src.LastName}");
Console.WriteLine(gm.Adapt<NameMerge>());

Console.WriteLine("\n8. 自定义映射(双向映射)");
TypeAdapterConfig<Gmail, OutLook>.NewConfig().TwoWays().Map(d => d.Mail, s => s.Email);
Gmail gmail = new() { Email = "lucy@gmail.com" };
OutLook outLook = new() { Mail = "tom@live.com" };
Console.WriteLine(gmail.Adapt<OutLook>());
Console.WriteLine(outLook.Adapt<Gmail>());

Console.WriteLine("\n9. Unflattening特性进行对象映射");
var person = new Person { Name = "张三", Age = 30, Address = new Address { City = "北京", Street = "长安街" } };
var personDto = person.Adapt<PersonDto>();
Console.WriteLine(personDto);

Console.WriteLine("\n10. 自定义表达式树");
var stu = new Student { Id = "1001", Name = "小林", Course = new Course { CourseName = "语文" } };
var stuDto = Helper.Mapper(stu, s => new StudentDto
{
  Name = s.Name,
  CourseName = s.Course.CourseName
});
Console.WriteLine(stuDto);

Console.WriteLine("\n11. 映射拦截事件");
TypeAdapterConfig<UserDto, UserDao>.NewConfig().AfterMapping((src, dest) => { Console.WriteLine("== 映射已完成 =="); });
Console.WriteLine(dto.Adapt<UserDao>().Name);


Console.ReadKey();